<template>
	<view class="container">
		<view class="top">
			<text class="title">优惠券列表</text>
		</view>
		<view class="coupon-list">
			<view class="coupon-item" v-for="(item, index) in msgList" :key="index" :style="{ animationDelay: index * 0.1 + 's' }">
				<view class="coupon-left">
					<view class="discount" v-if="item.triggerMoney <= 0">
						<text class="discount-num">{{item.discount}}</text>
						<text class="discount-text">折</text>
					</view>
					<view class="discount" v-else>
						<text class="discount-num">-{{item.preferentialMoney}}</text>
						<text class="discount-text">元</text>
					</view>
					<view class="condition" v-if="item.triggerMoney > 0">
						满{{item.triggerMoney}}元可用
					</view>
				</view>
				<view class="coupon-right">
					<view class="coupon-info">
						<view class="coupon-name">{{item.name}}</view>
						<view class="coupon-time"> 	
							<text>有效期：{{item.start}} 至 {{item.end}}</text>
						</view>
						<view class="coupon-detail">
							<text>剩余数量：{{item.num}}</text>
							<text>使用次数：{{item.size}}次</text>
						</view>
					</view>
					<view class="coupon-action">
						<button class="get-btn" @click="getCoupon(item)" v-if="item.status === 0 && item.num > 0" hover-class="button-hover">立即领取</button>
						<button class="unavailable-btn" v-else-if="item.num === 0">不可领取</button>
						<button class="got-btn" v-else>已领取</button>
					</view>
				</view>
				<view class="coupon-circle circle-left"></view>
				<view class="coupon-circle circle-right"></view>
			</view>
		</view>
	</view>
</template>

<script>
import request from '../../../uitls/request.js'

export default {
	data() {
		return {
			userInfo: null,
			msgList: [],
			userId: null,
		}
	},
	methods: {
		// 检查用户是否已有该优惠券
		checkUserCoupon(couponId) {
			return new Promise((resolve, reject) => {
				request({
					url: '/xsc/usercoupon/list',
					method: 'GET',
					data: {
						uId: this.userId,
						cId: couponId
					},
					success: (res) => {
						if (res.data.code === 200) {
							resolve(res.data.rows);
						} else {
							reject(new Error(res.data.msg || '查询失败'));
						}
					},
					fail: (err) => {
						reject(err);
					}
				});
			});
		},

		// 更新用户优惠券数量
		updateUserCoupon(userCouponId, num) {
			return new Promise((resolve, reject) => {
				request({
					url: '/xsc/usercoupon',
					method: 'PUT',
					data: {
						id: userCouponId,
						num: num + 1
						
					},
					success: (res) => {
						if (res.data.code === 200) {
							resolve();
						} else {
							reject(new Error(res.data.msg || '更新失败'));
						}
					},
					fail: (err) => {
						reject(err);
					}
				});
			});
		},

		// 添加新的用户优惠券
		addUserCoupon(couponId) {
			return new Promise((resolve, reject) => {
				request({
					url: '/xsc/usercoupon',
					method: 'POST',
					data: {
						uId: this.userId,
						cId: couponId,
						num: 1
					},
					success: (res) => {
						if (res.data.code === 200) {
							resolve();
						} else {
							reject(new Error(res.data.msg || '添加失败'));
						}
					},
					fail: (err) => {
						reject(err);
					}
				});
			});
		},

		async getCoupon(item) {
			try {
				// 1. 检查用户是否已有该优惠券
				const userCoupons = await this.checkUserCoupon(item.id);
				
				// 检查领取次数限制
				if (userCoupons && userCoupons.length > 0 && userCoupons[0].num >= 3) {
					uni.showToast({
						title: '每人只能领取三次',
						icon: 'none'
					});
					return;
				}

				// 2. 更新优惠券数量
				await new Promise((resolve, reject) => {
					request({
						url: '/xsc/coupon',
						method: 'PUT',
						data: {
							id: item.id,
							num: item.num - 1,  // 只减少数量
							updateBy: this.userInfo?.userName
						},
						success: (res) => {
							if (res.data.code === 200) {
								item.num -= 1; // 更新本地数据
								resolve();
							} else {
								reject(new Error(res.data.msg || '领取失败'));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
				
				if (userCoupons && userCoupons.length > 0) {
					// 3. 如果已有优惠券，更新数量
					await this.updateUserCoupon(userCoupons[0].id, userCoupons[0].num);
					// 显示第几次领取
					uni.showToast({
						title: `领取成功，第${userCoupons[0].num + 1}次领取，每人只能领3次`,
						icon: 'success',
						duration: 2000
					});
				} else {
					// 4. 如果没有优惠券，添加新的
					await this.addUserCoupon(item.id);
					// 显示第一次领取
					uni.showToast({
						title: '领取成功，第1次领取，每人只能领3次',
						icon: 'success',
						duration: 2000
					});
				}
			} catch (error) {
				console.error('领取优惠券失败:', error);
				uni.showToast({
					title: error.message || '领取失败',
					icon: 'none'
				});
			}
		}
	},
	onLoad() {
		// 获取用户信息
		const userInfo = uni.getStorageSync('userInfo');
		this.userInfo = userInfo;
		this.userId = userInfo?.id;
		
		// 输出用户ID到控制台
		console.log('当前用户ID:', this.userId);
		console.log('完整用户信息:', this.userInfo);
		
		const that = this
		request({
			url: '/xsc/coupon/list',
			method: 'GET',
			data: {
				pageNum: 1,
				pageSize: 100
			},
			success(res) {
				const result = res.data;
				if (result.code == 200) {
					that.msgList = result.rows.filter(item => item.status === 0);
				}
			}
		})
	}
}
</script>

<style>
.container {
	min-height: 100vh;
	background: linear-gradient(to bottom, #FF7500 0%, #FF7500 200rpx, #f5f5f5 200rpx);
}

.top {
	width: 100%;
	height: 200rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
}

.title {
	color: #ffffff;
	font-size: 40rpx;
	font-weight: bold;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.coupon-list {
	padding: 20rpx;
	margin-top: -100rpx;
}

.coupon-item {
	display: flex;
	background-color: #ffffff;
	border-radius: 20rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	overflow: hidden;
	position: relative;
	animation: slideIn 0.5s ease-out forwards;
	opacity: 0;
	transform: translateY(20rpx);
}

@keyframes slideIn {
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.coupon-left {
	width: 220rpx;
	background: linear-gradient(135deg, #FF875C 0%, #FF6B3D 100%);
	padding: 30rpx 20rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;
}

.discount {
	display: flex;
	align-items: baseline;
}

.discount-num {
	color: #ffffff;
	font-size: 72rpx;
	font-weight: bold;
	text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.discount-text {
	color: #ffffff;
	font-size: 36rpx;
	margin-left: 4rpx;
}

.condition {
	color: #ffffff;
	font-size: 24rpx;
	margin-top: 10rpx;
	background: rgba(255, 255, 255, 0.2);
	padding: 4rpx 12rpx;
	border-radius: 20rpx;
}

.coupon-right {
	flex: 1;
	padding: 30rpx;
	display: flex;
	justify-content: space-between;
	background: linear-gradient(to right, #FFF3EB 0%, #FFF8F5 100%);
	position: relative;
}

.coupon-info {
	flex: 1;
}

.coupon-name {
	font-size: 34rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 16rpx;
}

.coupon-time {
	font-size: 26rpx;
	color: #666666;
	margin-bottom: 16rpx;
	display: flex;
	align-items: center;
}

.coupon-detail {
	font-size: 26rpx;
	color: #999999;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.coupon-action {
	display: flex;
	align-items: center;
	padding-left: 20rpx;
}

.get-btn {
	background: linear-gradient(135deg, #FF8F6C 0%, #FF6B3D 100%);
	color: #ffffff;
	font-size: 28rpx;
	padding: 12rpx 36rpx;
	border-radius: 30rpx;
	border: none;
	box-shadow: 0 4rpx 12rpx rgba(255, 143, 108, 0.3);
	transition: all 0.3s ease;
}

.button-hover {
	transform: scale(0.95);
	box-shadow: 0 2rpx 6rpx rgba(255, 143, 108, 0.2);
}

.got-btn {
	background: #D9D9D9;
	color: #ffffff;
	font-size: 28rpx;
	padding: 12rpx 36rpx;
	border-radius: 30rpx;
	border: none;
}

.coupon-circle {
	position: absolute;
	width: 40rpx;
	height: 40rpx;
	background-color: #f5f5f5;
	border-radius: 50%;
	top: 50%;
	transform: translateY(-50%);
}

.circle-left {
	left: 200rpx;
}

.circle-right {
	right: 0;
}

/* 添加优惠券边缘的虚线效果 */
.coupon-item::after {
	content: '';
	position: absolute;
	left: 200rpx;
	top: 0;
	bottom: 0;
	width: 2rpx;
	background: repeating-linear-gradient(
		to bottom,
		#FF875C 0,
		#FF875C 10rpx,
		transparent 10rpx,
		transparent 20rpx
	);
}

.unavailable-btn {
	background: #CCCCCC;
	color: #ffffff;
	font-size: 28rpx;
	padding: 12rpx 36rpx;
	border-radius: 30rpx;
	border: none;
	opacity: 0.8;
}
</style>